package com.zzb.myshowme.view.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zzb.myshowme.R;
import com.zzb.myshowme.presenter.SendSecurityCodePresenter;
import com.zzb.myshowme.presenter.impl.SendSecurityCodePresenterImpl;
import com.zzb.myshowme.utils.CustomToast;
import com.zzb.myshowme.view.IView.SendSecurityCodeView;
import com.zzb.myshowme.view.activity.SendSecurityCodeActivity;
import com.zzb.myshowme.wiget.ProgressDialogView;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * 发送验证码
 * create an instance of this fragment.
 */
public class SendSecurityCodeFragment extends Fragment implements View.OnClickListener, SendSecurityCodeView {

    View view;
    String type;
    String phone;//手机号码

    boolean bool_phone = false;//用来表示是否正确
    boolean bool_code = false;

    TextView title_textV;
    TextView getcode_textV;
    Button next_button;
    ImageView back_imageV;
    EditText phone_editText;
    EditText code_editText;

    private SendSecurityCodePresenter sendSecurityCodePresenter;

    public SendSecurityCodeFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendSecurityCodePresenter = new SendSecurityCodePresenterImpl(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Intent intent=getActivity().getIntent();
        type = intent.getStringExtra("type");
        view = inflater.inflate(R.layout.fragment_send_security_code, container, false);
        initView(view);
        iniSMSSDK();

        return view;
    }

    private void initView(View view) {
        title_textV = (TextView) view.findViewById(R.id.title_textV);
        if(type.equals("register")){
            title_textV.setText("注册");
        }else if(type.equals("password")){
            title_textV.setText("找回密码");
        }

        ProgressDialogView.Initial(getActivity(), "正在验证");

        back_imageV = (ImageView) view.findViewById(R.id.back_imageV);
        phone_editText = (EditText) view.findViewById(R.id.phone_editText);
        code_editText = (EditText) view.findViewById(R.id.code_editText);
        getcode_textV = (TextView) view.findViewById(R.id.getcode_textV);
        next_button = (Button) view.findViewById(R.id.next_button);

        back_imageV.setOnClickListener(this);
        getcode_textV.setOnClickListener(this);
        next_button.setOnClickListener(this);

        /**
         * 判断手机号码是否够11位
         */
        phone_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11) {
                    bool_phone = true;
                } else {
                    bool_phone = false;
                }

                if (bool_code && bool_phone) {
                    next_button.setEnabled(true);
                } else {
                    next_button.setEnabled(false);
                }
            }
        });

        /**
         * 判断验证码是否够4位
         */
        code_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 4) {
                    bool_code = true;
                } else {
                    bool_code = false;
                }

                if (bool_code && bool_phone) {

                    next_button.setEnabled(true);
                } else {

                    next_button.setEnabled(false);
                }
            }
        });
    }

    /**
     * 初始化短信sdk
     */
    private void iniSMSSDK() {

        SMSSDK.initSDK(getActivity(), "add91b1ca379", "9c4250259e8bdabb1e52bf867ab17781", true);
        sendSecurityCodePresenter.iniSMSSDK();
//        EventHandler eh = new EventHandler() {
//
//            @Override
//            public void afterEvent(int event, int result, Object data) {
//                Message m = new Message();
//                m.what = 2;
//                m.arg1 = event;
//                m.arg2 = result;
//                m.obj = data;
//                mHandler.sendMessage(m);
//            }
//        };
//        SMSSDK.registerEventHandler(eh); //注册短信回调
//        SMSSDK.getSupportedCountries();//获取短信目前支持的国家列表，在监听中返回
    }


    //onDestroyView() —— 当fragment中的视图被移除的时候，调用这个方法。
    //onDestroyView() -> onDetach()
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ViewGroup vg = (ViewGroup) view.getParent();
            vg.removeView(view);
            sendSecurityCodePresenter.onDestroyView();
            SMSSDK.unregisterAllEventHandler();
        }
    }

    //onDetach() —— 当fragment和activity分离的时候，调用这个方法。
    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.getcode_textV:
                phone = phone_editText.getText().toString().trim();
                sendSecurityCodePresenter.getCode(phone);
                break;
            case R.id.next_button:
                goNext();
//                if(type.equals("register")){
//                    sendSecurityCodePresenter.isRegster(phone);
//                }else if(type.equals("password")){
//                    enterCode();
//                }
                break;
            case R.id.back_imageV:
                getActivity().finish();
                break;
        }
    }

    /**
     * 验证短信验证码
     */
    @Override
    public void enterCode() {
        String code = code_editText.getText().toString().trim();
        String phone = phone_editText.getText().toString().trim();
        sendSecurityCodePresenter.enterCode(phone, code);
    }

    @Override
    public void showProgress() {
        ProgressDialogView.show();
    }

    @Override
    public void hideProgress() {
        ProgressDialogView.dismiss();
    }

    /**--------------P 返回到 v 的 回调接口 --------------------***/
    /**
     * 刷新验证码时间
     */
    @Override
    public void updateCodeTextTime(int time) {
        getcode_textV.setText("重新发送(" + time + ")");
    }

    /**
     * 发送验证码倒计时后 设置文本内容
     */
    @Override
    public void setCodeText(String str){
        getcode_textV.setText(str);
    }

    /**
     * 设置验证码按钮是否使能
     */
    @Override
    public void setCodeTextEnabled(boolean enable){
        if(enable == true){
            getcode_textV.setEnabled(true);
            getcode_textV.setTextColor(getResources().getColor(R.color.background_blue));
        }else {
            getcode_textV.setEnabled(false);
            getcode_textV.setTextColor(getResources().getColor(R.color.gary));
        }
    }

    @Override
    public void showToast(String msg){
        CustomToast.show(getActivity(), msg, Toast.LENGTH_LONG);
    }

    @Override
    public void showToastError(String msg){
        setCodeTextEnabled(true);
        CustomToast.show(getActivity(), msg, Toast.LENGTH_LONG);
    }

    @Override
    public void goNext(){
        if(type.equals("register")){
            ((SendSecurityCodeActivity) getActivity()).phone = phone;//跳转前先保存一下
            ((SendSecurityCodeActivity) getActivity()).gotoPhoneRegsterToMessgae();
        }else if(type.equals("password")){
            ((SendSecurityCodeActivity) getActivity()).phone = phone;//跳转前先保存一下
            ((SendSecurityCodeActivity) getActivity()).gotoGetPassword();
        }
    }
}
